package ai.weed.qrcode.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author zhong.wang
 * @date 2025/10/30
 **/
@Component
@Data
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.refresh-expiration}")
    private Long refreshExpiration;

    // 生成 Token（含 openid）
    public String generateToken(String openid) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("openid", openid);
        return createToken(claims, expiration);
    }

    // 生成刷新 Token
    public String generateRefreshToken(String openid) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("openid", openid);
        return createToken(claims, refreshExpiration);
    }

    private String createToken(Map<String, Object> claims, Long expireTime) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject("user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    // 解析 Token 获取 openid
    public String getOpenidFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return claims.get("openid", String.class);
    }

    // 验证 Token 是否有效
    public Boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 在 JwtUtil 中添加方法
    public Long getExpirationTime(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return claims.getExpiration().getTime() / 1000; // 秒
    }
}